package com.xyhuo.leetcode.december;

import com.xyhuo.leetcode.common.ListNode;

import java.util.ArrayList;
import java.util.List;

/**
 * 删除链表的倒数第n个节点
 * https://leetcode.cn/problems/remove-nth-node-from-end-of-list/
 *
 * @time 2023/12/6
 */
public class RemoveNthFromEnd {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        List<ListNode> list = new ArrayList<>();
        ListNode tmp = head;
        while (tmp != null) {
            list.add(tmp);
            tmp = tmp.next;
        }
        int size = list.size();
        int targetIndex = size - n;
        if (targetIndex == 0) {
            if (size == 1) {
                return null;
            }
            return list.get(1);
        }
        if (targetIndex + 1 < size) {
            list.get(targetIndex - 1).next = list.get(targetIndex + 1);
        } else {
            list.get(targetIndex - 1).next = null;
        }
        return head;
    }

}
